package cn.starremote.component.utils;


import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;

/**
 * @Title: ZipUtils
 * @Description: zip 文件压缩 ， 支持加密
 * @author wangjw
 */
public class ZipUtils {

//    public static void main(String[] args) {
//        zipFilesAndEncrypt("/Users/wangjw/Documents/test.csv", "/Users/wangjw/Documents/test.zip", "test123!");
//    }

    /**
     * @param srcFileName 待压缩文件路径 或 文件夹路径
     * @param zipFileName zip路径+文件名
     * @param password    加密密码
     * @return
     * @Title: zipFilesAndEncrypt
     * @Description: 将指定路径下的文件压缩至指定zip文件，并以指定密码加密,若密码为空，则不进行加密保护
     */
    public static void zipFilesAndEncrypt(String srcFileName, String zipFileName, String password) {

        if (StringUtils.isEmpty(srcFileName) || StringUtils.isEmpty(zipFileName)) {
            System.out.println("请求的压缩路径或者文件名有误");
            return;
        }
        try {
            ZipParameters parameters = new ZipParameters();
            ZipFile zipFile;
            if (StringUtils.isNotEmpty(password)) {
                parameters.setEncryptFiles(true);
                //加密方式
                parameters.setEncryptionMethod(EncryptionMethod.AES);
                zipFile = new ZipFile(zipFileName, password.toCharArray());
            } else {
                zipFile = new ZipFile(zipFileName);
            }
            ArrayList<File> filesToAdd = getFiles(srcFileName);
            zipFile.addFiles(filesToAdd, parameters);
        } catch (ZipException e) {
            new File(zipFileName).deleteOnExit();
            throw new RuntimeException(e);
        }
        System.out.println("文件压缩完成！");
    }

    //通过路径获取压缩文件集合
    private static ArrayList<File> getFiles(String srcFileName) {
        ArrayList<File> filesToAdd = new ArrayList<>();
        File file = new File(srcFileName);
        File[] files;
        if (file.isDirectory()) {
            files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                filesToAdd.add(new File(files[i].getPath()));
                System.out.println("添加压缩文件：" + files[i].getPath());
            }
        } else {
            filesToAdd.add(new File(file.getPath()));
        }

        return filesToAdd;
    }

}